#coding=utf-8
from BeautifulSoup import BeautifulSoup 
from httplib2 import Http
from urllib import urlencode
from sdsource.exception import NoWebPageError,NoFileError
from suggest import get_market
from sdsource.models import Price
from decimal import Decimal

url = 'http://biz.finance.sina.com.cn/company/history.php'

def get_warrant_soup(code, year, quanter, try_times=10, encoding='gb18030'):
    
    symbol = get_market(code) + code
    #print symbol
    
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    data = dict(year=year, quanter=quanter, symbol=symbol)
    
    h = Http()
    
    for i in range(try_times):
        try:
            resp, content = h.request(url, "POST", headers=headers, body=urlencode(data))
        except Exception, e:
            print e
        else:
            if resp.status != 200:
                print 'status:',resp.status
                continue
            
            if resp['content-type'] and not resp['content-type'].startswith('text'): 
                print 'content-type:',resp['content-type']
                continue
            
            htmltext = content.decode(encoding, 'ignore')
            s = BeautifulSoup(htmltext)
            return s
            
def get_prices_from_soup(soup):

    def get_s(item):
        while True:
            r = item.string
            if r: return r.strip()
            item = item.contents[0]
            
    def get_price_from_row(row):
        
        r = []
        tds = row.findAll('td')

        for td in tds:
            r.append(get_s(td))

        if not r[0]:
            td0 = tds[0]
            rq = td0.contents[0].contents[1].string.strip()
            r[0] = rq
            
        for i in range(len(r)):
            r[i] = r[i].encode('u8')
        
        p = Price()
        
        p.date = r[0]
        
        p.open = float(r[1])
        p.highest = float(r[2])
        p.close = float(r[3])
        p.lowest = float(r[4])
        
        p.volume = int( Decimal(r[5]) * 100 )
        p.amount = int( Decimal(r[6]) * 10000 )   

        return p

    ps = []
    
    t = unicode('日期', 'u8')
    rq = soup.find(text = t)
    #如果在该季度内没有交易
    if not rq:return None 
    
    #与parse 其他股票历史价格html页面不同之处:就下一句
    table = rq.parent.parent.parent
    ###
    
    trs = table.findAll('tr')[2:]

    for tr in trs:
        p = get_price_from_row(tr)
        ps.append(p)

    ps.reverse()
    return ps    

def get_warrent_prices_by_jd(code, year, jd):
    
    sp = get_warrant_soup(code, year, jd)
    return get_prices_from_soup()
